################################################################################
# Judicial Ideology as Text -- Appendix Table 4 (Dynamic Wordshoal Betas)
# Truscott & Romano
# Updated February 2025
################################################################################

################################################################################
# Necessary Packages & Dependencies
################################################################################

source('R/truscott_romano_source.R')

################################################################################
# Table A4 (Dynamic Betas)
################################################################################

beta_high <- data.frame()

for (term in 1:length(wordshoals_dynamic[['High']])){

  temp_betas <- wordshoals_dynamic[['High']][[term]]$beta
  temp_dockets <- levels(wordshoals_dynamic[['High']][[term]]$groups)
  temp_combined <- data.frame(term = names(wordshoals_dynamic[['High']][term]),
                              beta = temp_betas,
                              docket = temp_dockets)
  beta_high <- bind_rows(beta_high, temp_combined)

}


important_cases <- which(abs(beta_high$beta) > quantile(abs(beta_high$beta), 0.95))

beta_high <- beta_high[important_cases,] %>%
  left_join(decisions %>% dplyr::select(case_name, docket), by = c('docket')) %>%
  distinct(docket, .keep_all = T) %>%
  dplyr::select(term, docket, case_name, beta) %>%
  unique() %>%
  mutate(beta = round(abs(beta), 3)) %>%
  arrange(beta)

beta_dynamic <- tibble(
  Term = c(beta_high$term),
  Docket = c(beta_high$docket),
  `Case Name` = c(beta_high$case_name),
  `Beta` = c(beta_high$beta)
)

table_A4_text <- stargazer(beta_dynamic, type = 'text', summary = F, rownames = F)

table_A4_latex <- stargazer(beta_dynamic, type = "latex", summary = FALSE, rownames = FALSE, label = 'tab:table_A4', title = 'Dynamic Wordshoal Summary Outputs by High Beta Estimate', style = 'apsr') # As LaTex

writeLines(table_A4_text, 'tables/table_A4_text.txt', sep = '\n')
writeLines(table_A4_latex, 'tables/table_A4_latex.txt', sep = '\n')
